var current_cat = 0;
var current_year = 2011;
var markersArray = [];
var cats_array = [];
var loc_address = "";
var loc_str = "(identificando...)";
var sel_latLong;
var is_init = true;
var n_rw = 0;

$(document).ready(function() {
	$.fancybox.showActivity();
	$("#marker-tooltip").mouseover(function(){
	    $(this).hide();
	});
	
	$("#marker-tooltip").hide();
	
  	/* -- Mapa -- */
    $("#map").css({
	    height: 550,
	    width: 1000,
	    position: 'absolute',
	    top: 40,
	    left: 160
    });
    var myLatLng = new google.maps.LatLng(25, 16);
    RewindMap.init('#map', myLatLng, 2);
	
    /* -- Geocoder autocompletion -- */
    $('#demo2_location').geo_autocomplete({
    	geocoder_region: 'Chile',
    	geocoder_language: 'es',
    	geocoder_types: 'street_address,route,intersection,political,country,colloquial_area,locality,sublocality,neighborhood,premise,subpremise,natural_feature,airport,park',
		select: function(_event, _ui) {
			if (_ui.item.viewport){
				RewindMap.map.setZoom(12);
				RewindMap.map.fitBounds(_ui.item.viewport);
			}
		}
	});
	
	/* -- Category sidebar -- */
  $("#cats li").click( function() {
    prev_cat = current_cat;
    current_cat = parseInt( $(this).attr("id") );

    if( $(this).hasClass("category-selected") ){
      cat_rem(current_cat);
      $(this).removeClass("category-selected");
      reload_markers();
    } else {
      cat_add(current_cat);
      $(this).addClass("category-selected");
      if(cats_array.length == 1) {
        load_markers(current_year, current_cat);
      } else {
        append_markers(current_year, current_cat);
      }
    }
	});

	$("#nav li ul li").click(function(){
		current_year = parseInt( $(this).text() );
		load_yearly_markers(current_year);
	    $("#year-header").fadeOut("fast", function(){

	        $("#year-header").text(current_year);
	        $("#year-header").fadeIn("fast");
	    });

	});

	$("#year-prev").click(function(){
    	if(current_year > 1900){
			current_year-=1;
			$("#year-header").fadeOut("fast", function(){
    	        $("#year-header").text(current_year);
    	        $("#year-header").fadeIn("fast");
    	        load_yearly_markers(current_year);
    	    });
		}
	});

	$("#year-next").click(function(){
		if(current_year < 2011){
			current_year+=1;
			$("#year-header").fadeOut("fast", function(){
    	        $("#year-header").text(current_year);
    	        $("#year-header").fadeIn("fast");
    	        load_yearly_markers(current_year);
    	    });

		}
	});
	
	load_latests();
	$.fancybox.hideActivity();

}); //end doc.onReady

var RewindMap = {
  map: null,
  ounds: null,
  geocoder: null
}

RewindMap.init = function(selector, latLng, zoom) {
  var myOptions = {
    zoom:zoom,
    center: latLng,
    mapTypeControl: false,
    navigationControl: true,
    mapTypeId: google.maps.MapTypeId.HYBRID,
    streetViewControl: true
  }
  this.map = new google.maps.Map($(selector)[0], myOptions);
  this.map.setTilt(45);
  this.geocoder = new google.maps.Geocoder();
  this.bounds = new google.maps.LatLngBounds();


  //listener para agregar los marcadores touch-unfriendly
  google.maps.event.addListener(RewindMap.map, 'rightclick', function(event) {
	sel_latLong = event.latLng;
    $("#popout").css('position', 'absolute');
    $("#popout").css('z-index', '3000');
    $("#popout").css('width', 150);
    $("#popout").css('padding', 10);
    $("#popout").css('background-color', 'rgba(20,20,20,0.6)');
    $("#popout").css('top', event.pixel.y+104);
    $("#popout").css('left', event.pixel.x+192);
    $("#popout").fadeIn();
    $("#popout").click(function(){
      publish(sel_latLong);
    });
  	    
    $("#popout").mouseenter(function(){
      $(this).css('background-color', 'rgba(20,20,20,0.8)');
    });
  	    
    $("#popout").mouseleave(function(){
      $(this).fadeOut('fast');
    });
	  	    
  });

}//init

/**
 * Agregar un marcador en la posición indicada
 * @arg location un objeto LatLong
 */
function publish(loc){
  var image = "assets/cat-"+ current_cat + ".png";
  var shadow = "assets/cat-"+ current_cat + "_shadow.png";
  $("#popout").fadeOut();
  
  var url = "/user/publish?cat=" + current_cat + "&year=" + current_year + "&lat=" + loc.lat() + "&lng=" + loc.lng();
  console.log(url);
  $.fancybox.showActivity();

  $.fancybox({
    'autoDimensions'  	: false,
    'width'           	: 350,
    'height'           	: 580,
    'async'             : false,
    'transitionIn'	  	: 'fade',
    'transitionOut'	  	: 'fade',
    'scrolling'         : 'no',
    'overlayShow'       : false,
    'type'              : 'iframe', //para permitir subir archivos
    'href'              : url
  });
  $.fancybox.hideActivity();
}
  
function load_latests(){ //with clearing
	//clear_overlays();
	get_markers("/rest/post/latests/50.xml");	
}

function append_markers(year, cat){//FIXME: add pagination
	get_markers("/rest/post/year/"+ year + "/category/"+ cat +"/limit/50.xml");
}

function load_markers(year, cat){//FIXME: add pagination
	clear_overlays();
	append_markers(year, cat);
}

function load_yearly_markers(year){
	clear_overlays();
  $("#cats li").removeClass("category-selected");
  cat_clear();
	get_markers("/rest/post/year/"+ year +"/limit/50.xml");
}

function reload_markers(){
	clear_overlays();
	for(i in cats_array){
		append_markers(current_year, i);
  }
}

//function refresh_markers() //without loading

function get_markers(url){
    var marks = 0;
    console.log("loading:" + url);
    $.fancybox.showActivity();
		$.get(url, function(dom){
      $.fancybox.hideActivity();
      
			$(dom).find("entry").each(function(){
				marks += 1;
        var id = $(this).attr("id");
		    var title = $(this).find('title').text();
		    var lat = $(this).find('latitude').text();
		    var lng = $(this).find('longitude').text();
		    var year = $(this).find('year').text();
		    var category = $(this).find('category').attr("id");

			    var point = new google.maps.LatLng(parseFloat(lat),parseFloat(lng));

		        if(lat != 0 && lng != 0){
		            RewindMap.bounds.extend(point);
		        }

		        var marker = new google.maps.Marker({
		          position: point,
		          map: RewindMap.map/*,
		          icon: image,
		          shadow: shadow*/
		        });

		        markersArray.push(marker);

		        google.maps.event.addListener(marker, 'click', function(event){
		        	show_post(id);
		        });
	        
		        google.maps.event.addListener(marker, 'mouseover', function(event){
		           $("#marker-tooltip").show();//('fast');
		           $("#marker-tooltip strong").text(title);
		        });

		        google.maps.event.addListener(marker, 'mouseout', function(event){
		           $("#marker-tooltip").hide();//('fast');
		           $("#marker-tooltip strong").text('');
		        });

			}); //each
		  
		  if(marks > 0){
		    RewindMap.map.fitBounds(RewindMap.bounds);
		    n_rw += marks;
		  }
		  if(RewindMap.map.getZoom() > 17){
		      RewindMap.map.setZoom(17);
		  }
		  
		  
	}); //GET

}

function clear_overlays() {
  console.log("--clear--");
  $("#cats-entries").empty();
  if (markersArray) {
    for (i in markersArray) {
      markersArray[i].setMap(null);
    }
  }
}

function attach_trigger(loc){
 var point = new google.maps.LatLng(loc.lat(), loc.lng());
 $("#trigger-map").click(function(){
     RewindMap.map.setZoom(12);
     RewindMap.map.setCenter(point);
     $('#demo2_location').autocomplete( "close" );
     $("#trigger-map").click(function(){});
 });
}

function randomMinToMax(min, max){
	 var range = (max - min) + 1;
	 return Math.floor(Math.random()*range+min);
}

function cat_add(cat_n){ //O(n)
    for (i in cats_array) {
      if(cats_array[i] == cat_n){
        return;
      }
    }
    cats_array.push(cat_n);
}

function cat_rem(cat_n){
    ind = cats_array.indexOf(cat_n);
    cats_array.splice(ind, 1);
    if(cats_array.length == 0){
        current_cat = -1;
    } else {
        current_cat = cats_array[cats_array.length -1];
    }
}

function cat_clear(){
  while(cats_array.length > 0){
    cats_array.pop();
  }
}

function showAll(){
  //pass
}
